package com.beyondsoft.mcms.web;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.persistence.TypedQuery;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.joda.time.format.DateTimeFormat;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

import com.beyondsoft.mcms.common.Constants;
import com.beyondsoft.mcms.domain.Category;
import com.beyondsoft.mcms.domain.Item;
import com.beyondsoft.mcms.domain.MemberInfo;
import com.beyondsoft.mcms.reference.AuthRole;
import com.beyondsoft.mcms.service.MemberInfoServiceImpl;

@RequestMapping(value = "/register**")
@Controller
public class RegisterController {
	
	/*
	 * 进入注册页面
	 */
    @RequestMapping(params = "form", produces = "text/html")
    public String register(Model uiModel, HttpServletRequest request) {
    	MemberInfo memberInfo = new MemberInfo();
        
    	populateEditForm(uiModel, memberInfo);
    	List<String[]> dependencies = new ArrayList<String[]>();
    	
    	List<Item> items = Item.findItemsByCategoryAndIsValid(Category.findCategory(new Long(Constants.POSITION_TYPE)), true).getResultList();
        if (items==null || items.size() == 0) {
            dependencies.add(new String[] { "positiontype", "items" });
        }
                
        items = Item.findItemsByCategoryAndIsValid(Category.findCategory(new Long(Constants.BUSINESS_TYPE)), true).getResultList();
        if (items==null || items.size() == 0) {
            dependencies.add(new String[] { "businesstype", "items" });
        }
        
        String contextPath = request.getContextPath();
        uiModel.addAttribute("contextPath", contextPath);
        uiModel.addAttribute("dependencies", dependencies);
        return "register/index";
    }
    
    /*
     * 保存注册信息
     */
    @RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid MemberInfo memberInfo, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, memberInfo);
            return "register/index";
        }
        uiModel.asMap().clear();
        
        memberInfo.setRigesterDate(new Date());
        memberInfo.setCreatedBy(memberInfo.getMemberName()); //自己创建自己
        memberInfo.setPositionType(Item.findItem(new Long(Constants.POSITION_PRE))); 
        
        new MemberInfoServiceImpl().saveMemberInfo(memberInfo);
        
        //return "redirect:/register/" + encodeUrlPathSegment(memberInfo.getId().toString(), httpServletRequest);
        return "register/success";
    }
    
    @RequestMapping(produces = "text/html")
    public String show(Model uiModel) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String username = auth.getName();
        MemberInfo memberInfo = MemberInfo.findMemberInfoesByUsernameEquals(username).getSingleResult();
        
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("memberinfo", memberInfo);
        uiModel.addAttribute("itemId", memberInfo.getId());
        return "register/show";
    }
    
    /*
     * 进入注册信息修改页面
     */
    @RequestMapping(value="/{id}", params = "form" , method = RequestMethod.GET)
    public String updateForm(Model uiModel) {
    	String username = SecurityContextHolder.getContext().getAuthentication().getName();
    	MemberInfo memberInfo = MemberInfo.findMemberInfoesByUsernameEquals(username).getSingleResult();
    	populateEditForm(uiModel, memberInfo);
    	return "register/update";
    	
    }
    
    @RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid MemberInfo memberInfo, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, memberInfo);
            return "register/update";
        }
        
        String operator = SecurityContextHolder.getContext().getAuthentication().getName();
        if (!operator.equals(memberInfo.getUsername())){
        	return "dataAccessFailure";
        }
        
        uiModel.asMap().clear();
        memberInfo.setUpdatedBy(operator); 
        memberInfo.setUpdateDate(new Date());
        memberInfo.merge();
        //return "redirect:/memberinfoes/" + encodeUrlPathSegment(memberInfo.getId().toString(), httpServletRequest);
        return "redirect:/register";
    }
    
    
    void addDateTimeFormatPatterns(Model uiModel) {
        uiModel.addAttribute("memberInfo_rigesterdate_date_format", DateTimeFormat.patternForStyle("MM", LocaleContextHolder.getLocale()));
        uiModel.addAttribute("memberInfo_updatedate_date_format", DateTimeFormat.patternForStyle("MM", LocaleContextHolder.getLocale()));
    }
    
    void populateEditForm(Model uiModel, MemberInfo memberInfo) {
        uiModel.addAttribute("memberInfo", memberInfo);
        addDateTimeFormatPatterns(uiModel);
        TypedQuery<Item> businesstypes = Item.findItemsByCategoryAndIsValid(Category.findCategory(new Long(Constants.BUSINESS_TYPE)), true);
        uiModel.addAttribute("businesstypes", businesstypes.getResultList());
        uiModel.addAttribute("positiontypes", Item.findItemsByCategoryAndIsValid(Category.findCategory(new Long(Constants.POSITION_TYPE)), true).getResultList());
    }
    
    String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }
    
}
